package com.beiing.tianshuai.tianshuai.interest;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.adapter.InterestCategoriesDialogAdapter;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.entity.CodeBean;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.interest.entity.InterestCategoriesBean;
import com.beiing.tianshuai.tianshuai.interest.entity.InterestVideoPublishBean;
import com.beiing.tianshuai.tianshuai.interest.presenter.InterestPublishPresenter;
import com.beiing.tianshuai.tianshuai.interest.view.InterestPublishViewImpl;
import com.beiing.tianshuai.tianshuai.util.InterestVideoCheckUtil;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.widget.CustomProgressDialog;
import com.beiing.tianshuai.tianshuai.widget.GlideImageLoader;
import com.beiing.tianshuai.tianshuai.widget.RoundAngleImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.tianshuai.gallerypic.config.GalleryConfig;
import com.tianshuai.gallerypic.config.GalleryPick;
import com.tianshuai.gallerypic.inter.IHandlerCallBack;
import com.zxy.tiny.Tiny;
import com.zxy.tiny.callback.FileCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.bingoogolapple.bgabanner.BGAOnNoDoubleClickListener;

public class InterestPublishActivity extends BaseActivity implements InterestPublishViewImpl {

    @BindView(R.id.rai_cover)
    RoundAngleImageView mRaiCover;
    @BindView(R.id.toolbar_iv_back)
    ImageView mToolbarIvBack;
    @BindView(R.id.toolbar_tv_title)
    TextView mToolbarTvTitle;
    @BindView(R.id.tv_category)
    TextView mTvCategory;
    @BindView(R.id.toolbar_btn_publish)
    TextView mToolbarBtnPublish;
    @BindView(R.id.btn_select_cover)
    Button mBtnSelectCover;
    @BindView(R.id.rl_cover_container)
    RelativeLayout mRlCoverContainer;
    @BindView(R.id.et_video_url)
    EditText mEtVideoUrl;
    @BindView(R.id.et_video_title)
    EditText mEtVideoTitle;
    @BindView(R.id.rl_categories_container)
    RelativeLayout mRlCategoriesContainer;
    @BindView(R.id.et_video_describe)
    EditText mEtVideoDescribe;
    @BindView(R.id.btn_help)
    ImageButton mBtnHelp;

    private static final String TAG = "InterestPublishActivity";

    /**
     * 权限检查请求码
     */
    private static final int PERMISSIONS_REQUEST_READ_CONTACTS = 100;

    /**
     * presenter
     */
    private InterestPublishPresenter mPresenter;

    /**
     * 上传视频信息的实体bean
     */
    private InterestVideoPublishBean mInterestVideoPublishBean;

    /**
     * 当前登录的用户id
     */
    private String mUid;

    /**
     * 分类弹出框适配器
     */
    private InterestCategoriesDialogAdapter mCategoriesDialogAdapter;

    /**
     * 底部分类dialog
     */
    private Dialog mDialog;

    /**
     * 上传请求重连次数
     */
    private int retryConnect = 0;

    /**
     * 上传帮助fragment
     */
    private VideoPublishHelperFragment mHelpFragment;

    /**
     * 输入法manager
     */
    private InputMethodManager imm;

    public static void star(Context context){
        Intent intent = new Intent(context, InterestPublishActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_interest_publish;
    }

    @Override
    protected void init() {

        imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        mInterestVideoPublishBean = new InterestVideoPublishBean();
        mUid = UserInfoBean.getUid(mContext);
        mInterestVideoPublishBean.setUid(mUid);
        mCategoriesDialogAdapter = new InterestCategoriesDialogAdapter(mContext);

        initToolbar();
        initListener();
        initPresenter();
    }

    /**
     * 初始化Toolbar
     * <p>
     * 显示返回按钮
     * 修改标题
     * 设置右边的按钮text
     */
    private void initToolbar() {
        mToolbarIvBack.setVisibility(View.VISIBLE);
        mToolbarBtnPublish.setVisibility(View.VISIBLE);
        mToolbarBtnPublish.setText("发布");
        mToolbarTvTitle.setText("上传视频");
    }

    /**
     * 初始化点击事件
     */
    private void initListener() {
        // 帮助
        mBtnHelp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                View currentFocus = getCurrentFocus();
                if (currentFocus != null) {
                    imm.hideSoftInputFromWindow(currentFocus.getWindowToken(),0);
                }
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                if (mHelpFragment == null) {
                    mHelpFragment = VideoPublishHelperFragment.newInstance();
                    transaction.setCustomAnimations(R.anim.fade_in, R.anim.fade_out)
                            .add(R.id.fragment_container, mHelpFragment, mHelpFragment.getClass().getName())
                            .commit();
                } else {
                    transaction.setCustomAnimations(R.anim.fade_in, R.anim.fade_out)
                            .show(mHelpFragment)
                            .commit();
                }
            }
        });

        // 返回
        mToolbarIvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        // 发布
        mToolbarBtnPublish.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                publishVideo();
            }
        });

        // 选择封面
        mBtnSelectCover.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkSelfPermission();
            }
        });

        // 选择分类
        mRlCategoriesContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showCategoriesDialog();
            }
        });

        // 设置分类标签点击事件
        mCategoriesDialogAdapter.setListener(new InterestCategoriesDialogAdapter.OnInterestCategoriesDialogItemClickListener() {
            @Override
            public void onItemClickListener(InterestCategoriesBean.DataBean.NumberBean bean, int position, int oldPosition) {
                if (position == oldPosition) {
                    mDialog.dismiss();
                    return;
                }
                mCategoriesDialogAdapter.getNumberBean().setSelected(false);
                mCategoriesDialogAdapter.setNumberBean(bean);
                mCategoriesDialogAdapter.setOldPosition(position);
                bean.setSelected(true);
                mCategoriesDialogAdapter.notifyDataSetChanged();
                mDialog.dismiss();
                mTvCategory.setText(bean.getName());
                mInterestVideoPublishBean.setTid(bean.getId());
            }
        });
    }

    private void publishVideo() {
        File coverFile = mInterestVideoPublishBean.getCoverFile();
        if (coverFile == null) {
            showShortText("请选择视频封面");
            return;
        }
        String url = mEtVideoUrl.getText().toString().trim();
        if (TextUtils.isEmpty(url)) {
            showShortText("请输入视频链接");
            return;
        }
        String s = InterestVideoCheckUtil.iframeCode(url);
        LogUtils.i(s, TAG);
        String title = mEtVideoTitle.getText().toString().trim();
        if (TextUtils.isEmpty(title)) {
            showShortText("请输入标题");
            return;
        }
        String tid = mInterestVideoPublishBean.getTid();
        if (TextUtils.isEmpty(tid)) {
            showShortText("请选择分类");
            return;
        }
        String desc = mEtVideoDescribe.getText().toString().trim();
        if (TextUtils.isEmpty(desc)) {
            showShortText("请描述一下你的视频");
            return;
        }
        mPresenter.submitVideo(mUid, tid, title, desc, url, coverFile);
    }

    private void initPresenter() {
        mPresenter = new InterestPublishPresenter(this);
        mPresenter.getCategories();
    }

    // 动态权限申请
    private void checkSelfPermission() {
        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            LogUtils.i("需要授权", TAG);
            if (ActivityCompat.shouldShowRequestPermissionRationale(InterestPublishActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                LogUtils.i("拒绝过了", TAG);
                // 提示用户如果想要正常使用，要手动去设置中授权。
                showShortText("请在 设置-应用管理 中开启此应用的储存授权。");
            } else {
                LogUtils.i("进行授权", TAG);
                ActivityCompat.requestPermissions(
                        InterestPublishActivity.this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        PERMISSIONS_REQUEST_READ_CONTACTS
                );
            }
        } else {
            LogUtils.i("不需要授权", TAG);
            // 进行正常操作
            selectImage();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                LogUtils.i("同意授权", TAG);
                // 进行正常操作。
                selectImage();
            } else {
                LogUtils.i("拒绝授权", TAG);
            }
        }
    }

    private void selectImage() {
        List<String> path = new ArrayList<>();
        IHandlerCallBack iHandlerCallBack = new IHandlerCallBack() {
            @Override
            public void onStart() {
                LogUtils.i("----------------- 选图开始 -----------------", TAG);
            }

            @Override
            public void onSuccess(List<String> photoList) {
                String path = photoList.get(0);
                LogUtils.i(photoList.toString(), TAG);
                Tiny.FileCompressOptions tinyOptions = new Tiny.FileCompressOptions();
                tinyOptions.quality = 76;
                tinyOptions.isKeepSampling = true;
                tinyOptions.size = 100;
                Tiny.getInstance().source(path).asFile().withOptions(tinyOptions).compress(new FileCallback() {
                    @Override
                    public void callback(boolean isSuccess, String outfile) {
                        if (isSuccess) {
                            File coverFile = new File(outfile);
                            mInterestVideoPublishBean.setCoverFile(coverFile);
                            RequestOptions options = new RequestOptions()
                                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                                    .skipMemoryCache(false)
                                    .centerCrop()
                                    .override(800, 450);
                            Glide.with(mContext)
                                    .load(coverFile)
                                    .apply(options)
                                    .into(mRaiCover);
                            mBtnSelectCover.setText("更换封面");
                        } else {
                            showShortText("图片过大");
                        }
                    }
                });
            }

            @Override
            public void onCancel() {
                LogUtils.i("用户已取消", TAG);
            }

            @Override
            public void onFinish() {
                LogUtils.i("----------------- 选图结束 -----------------", TAG);
            }

            @Override
            public void onError() {
                LogUtils.e("----------------- 选图异常 -----------------", TAG);
            }
        };
        GalleryConfig galleryConfig = new GalleryConfig.Builder()
                .imageLoader(new GlideImageLoader())                // ImageLoader 加载框架（必填）
                .iHandlerCallBack(iHandlerCallBack)                 // 监听接口（必填）
                .provider("com.beiing.tianshuai.fileprovider")      // provider (必填)
                .pathList(path)                                     // 记录已选的图片
                .multiSelect(false)                                 // 是否多选   默认：false
                .crop(true, 16, 9, 1600, 900)  // 快捷开启裁剪功能，仅当单选 或直接开启相机时有效
                .isShowCamera(true)                                 // 是否现实相机按钮  默认：false
                .filePath("/TianShuai/Pictures")                    // 图片存放路径
                .build();
        GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(InterestPublishActivity.this);
    }

    /**
     * 弹出分类选择提示框
     */
    private void showCategoriesDialog() {
        mDialog = new Dialog(mContext, R.style.BottomDialog);
        @SuppressLint("InflateParams")
        View contentView = LayoutInflater.from(mContext).inflate(R.layout.dialog_interest_select_catgory, null);

        RecyclerView rvCategories = contentView.findViewById(R.id.rv_categories);
        final GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, 4);
        rvCategories.setLayoutManager(gridLayoutManager);
        rvCategories.setAdapter(mCategoriesDialogAdapter);

        mDialog.setContentView(contentView);
        ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels;
        contentView.setLayoutParams(layoutParams);
        Window window = mDialog.getWindow();
        if (window != null) {
            window.setGravity(Gravity.BOTTOM);
            window.setWindowAnimations(R.style.BottomDialog_Animation);
        }
        mDialog.show();
        mDialog.setCanceledOnTouchOutside(true);
    }

    @Override
    public void showProgress() {
        CustomProgressDialog.showLoading(mContext, "请稍后，正在努力加载...", true);
    }

    @Override
    public void hideProgress() {
        CustomProgressDialog.stopLoading();
    }

    @Override
    public void onRequestSuccess(InterestCategoriesBean bean) {
        List<InterestCategoriesBean.DataBean.NumberBean> number = bean.getData().getNumber();
        for (int i = 0, numberSize = number.size(); i < numberSize; i++) {
            InterestCategoriesBean.DataBean.NumberBean numberBean = number.get(i);
            if ("2".equals(numberBean.getStatus())) {
                number.remove(i);
                i--;
                numberSize = number.size();
            }
        }
        InterestCategoriesBean.DataBean.NumberBean typeBean = number.get(0);
        typeBean.setSelected(true);
        String name = typeBean.getName();
        String tid = typeBean.getId();
        mTvCategory.setText(name);
        mInterestVideoPublishBean.setTid(tid);
        mCategoriesDialogAdapter.setNumberBean(typeBean);
        mCategoriesDialogAdapter.updateData(number);
    }

    @Override
    public void onRequestFailed(Throwable throwable) {
        LogUtils.e(throwable.getMessage(), InterestPublishActivity.class.getName());
        if ((retryConnect < 5)) {
            retryConnect++;
            mPresenter.getCategories();
        } else {
            showShortText("获取分类失败");
            retryConnect = 0;
            finish();
        }
    }

    @Override
    public void submitVideoSuccess(CodeBean bean) {
        if (bean.getCode() == 200) {
            showShortText("提交成功，预计在1-2个工作日内通过审核~");
            Intent intent = new Intent();
            intent.putExtra("isPublishSuccess", true);
            intent.putExtra("tagName", mTvCategory.getText().toString());
            setResult(InterestFragment.REQUEST_CODE_PUBLISH_VIDEO, intent);
            finish();
        }
    }

    @Override
    public void submitVideoError(Throwable e) {
        LogUtils.e(e.getMessage(), TAG);
        showShortText("抱歉，上传失败~");
    }

    @Override
    public void onBackPressed() {
        boolean userVisibleHint = false;
        if (null != mHelpFragment){
            userVisibleHint = mHelpFragment.getUserVisibleHint();
        }
        if (userVisibleHint) {
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.setCustomAnimations(R.anim.fade_in, R.anim.fade_out)
                    .hide(mHelpFragment)
                    .commit();
            mHelpFragment.setUserVisibleHint(false);
        } else {
            super.onBackPressed();
        }
    }

    public void hideSelectFragment() {
        boolean userVisibleHint = mHelpFragment.getUserVisibleHint();
        if (userVisibleHint) {
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.setCustomAnimations(R.anim.fade_in, R.anim.fade_out)
                    .hide(mHelpFragment)
                    .commit();
            mHelpFragment.setUserVisibleHint(false);
        }
    }
}
